from decimal import Decimal
from yandex_geocoder import Client
from random import uniform
from kivy.clock import Clock
client = Client("69a38774-c9ce-49c9-a18e-eb542ffaa55e")
import datetime
from kivy.app import App
from kivy.uix.gridlayout import GridLayout 
# BoxLayout: it's in the python part, so you need to import it

from kivy.lang import Builder
Builder.load_string("""
<Container>
   rows: 11
   padding: 30
   spacing: 10
   x1: text_input1
   x2: text_input2
   x3: label1
   x4: label2
   x5: label3
   x6: label4
   x7: label5
   x8: label6
   Image:
      source: "1.png"
   TextInput:
      id: text_input1
      size_hint: 1, 0.5
      multiline: False
      font_size: 20
   TextInput:
      id: text_input2
      size_hint: 1, 0.5
      multiline: False
      font_size: 20
   Button:
      size_hint: 0.5, 0.5
      text: "Ввод"
      
      on_release:
         root.change_text()
   Label:
      id: label1
      text: "Расстояние:"
      font_size: 20
   Label:
      id: label2
      text: "Продолжительность:"
      font_size: 20
   Label:
      id: label3
      text: "Скорость маршрута:"
      font_size: 20
   Label:
      id: label4
      text: "Расчётная сложность:"
      font_size: 20
   Label:
      id: label5
      text: "Пульс:"
      font_size: 20
   Label:
      id: label6
      text: "Реальная сложность:"
      font_size: 20
   Button:
      size_hint: 0.2, 0.4
      text: "Сохранить"
      
      on_release:
         root.save()
""")
import requests
TOKEN = '5b3ce3597851110001cf62482ca61246451149f0acada8ef08363710'

def matrix(locations: list, profile=0):
    headers = {
        'Content-Type': 'application/json; charset=utf-8',
        'Accept': 'application/json',
        'Authorization': TOKEN
    }
    profile_dict = {
        0: 'driving-car',
        1: 'foot-walking'
    }
    data = {"locations":[i[::-1] for i in locations],"metrics":["distance","duration"],"units":"m"}
    res = requests.post(f'https://api.openrouteservice.org/v2/matrix/{profile_dict[profile]}',
                        headers=headers,
                        json=data).json()
    return dict(durations = res['durations'][0][1], distances = res['distances'][0][1])


url = ("https://dt.miet.ru/ppo_it/api/watch")
headers = {'X-Access-Tokens' : 'az4fvf7nzi1XPIsYiMEu'}
r = requests.get(url, headers=headers)
#{"code": 200, "data": {"pulse": {"min": 66.0, "max": 151.0, "avg": 108.0}}, "status": "ok"}
x = r.text.split(": ")
mi = float(x[4].split(",")[0])
ma = float(x[5].split(",")[0])
avg = float(x[6][:x[6].find("}")])

class Container(GridLayout):
    def change_text(self):
        global result, v, t, ras_sl, real_sl
        coord1 = client.coordinates(self.x1.text)
        coord2 = client.coordinates(self.x2.text)
        result = matrix([list(coord1), list(coord2)], 0)
        self.x3.text = "Расстояние" + " " + str(round(result["distances"] / 1000,2)) + " км"
        v = uniform(15, 25)
        self.x5.text = "Скорость маршрута:" + " " + str(round(v, 2)) + " км / ч"
        self.x4.text = "Продолжительность" + " " + str(round(result["distances"] / 1000/v*60,2)) + " минут"
        ras_sl = "легкая"
        if 25 >= round(result["distances"] / 1000) >= 11:
            ras_sl = "средняя"
        if round(result["distances"] / 1000) > 25:
            ras_sl = "сложная"        
        self.x6.text = "Расчётная сложность:" + " " + ras_sl
        t = uniform(mi, ma)
        self.x7.text = "Пульс:" + " " + str(round(t, 2))
        real_sl = "легкая"
        
        if 25 >= round(result["distances"] / 1000) >= 11 and abs(round(t, 2) - ma) > abs(round(t, 2) - avg):
            real_sl = "средняя"
        if round(result["distances"] / 1000) > 25 and abs(round(t, 2) - ma) < abs(round(t, 2) - avg):
            real_sl = "сложная"        
        self.x8.text = "Реальная сложность:" + " " + ras_sl        
    def save(self):
        global result, v, t, ras_sl, real_sl
        f = open("bike.txt", "a")
        x = datetime.datetime.now()
        f.write(str(x.day//10)+str(x.day%10)+"."+str(x.month//10)+str(x.month%10)+"."+str(x.year)+"\n")
        f.write("Длительность в километрах "+str(round(result["distances"] / 1000,2))+"\n")
        f.write("Время поездки "+str(round(result["distances"] / 1000/v*60,2))+"минут\n")
        f.write("Средняя скорость "+str(round(v, 2)) + " км / ч\n")
        f.write("Максимальный пульс "+str(ma) + " \n")
        f.write("Средний пульс "+str(avg) + " \n")
        f.write("Минимальный пульс "+str(mi) + " \n")
        f.write("Сложность расчётная "+str(ras_sl) + " \n")
        f.write("Сложность реальная "+str(real_sl) + " \n")
        f.write("")
        f.close()
        self.x1.text = ""
        self.x2.text = ""
        self.x3.text = "Расстояние:"
        self.x4.text = "Скорость маршрута:"
        self.x5.text = "Продолжительность:"
        self.x6.text = "Расчётная сложность:"
        self.x7.text = "Пульс:"
        self.x8.text = "Реальная сложность:"
class MyApp(App):   
    def build(self):
        return Container()
    
    
MyApp().run()

